const router = require('../../router');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    if(file.mimetype == 'image/png') {
      cb(null, path.resolve(__dirname, '../../../../db/__temp__'))
    } else {
      cb({ error: 'Mime type not supported' })
    }
    
  },
  filename: function(req, file, cb) {
    cb(null, `${Date.now()}.${file.originalname}`)
  }
})

/**
 * @openapi
 * /piper/upload/putImage:
    post:
      summary: 上传图片
      tags: 
        - putImage
      requestBody:
        required: true
        content: 
          application/json: 
            schema: 
              $ref: '#/components/schemas/putImage'
      responses:  
        '200':
          content:
            application/json:
              example:
                code: "0"
                data: ""
                msg: "成功"
                success: true
 */
router.post('/putImage', multer({
    storage: storage
}).single('img'), async function (req, res) {
  console.log('putImage', req.file);
    // 定时删除上传的图片
    
    setTimeout(() => {
      if(fs.existsSync(path.resolve(__dirname, `../../../../db/__temp__/${req.file.filename}`))) {
        fs.unlink(path.resolve(__dirname, `../../../../db/__temp__/${req.file.filename}`), function (err) {
          if (err) {
            console.error(`删除文件 ${req.file.filename} 失败，失败原因：${err}`)
          }
          console.log(`删除文件 ${req.file.filename} 成功`)
        });
      } else {
        console.log(`文件 ${req.file.filename} 不存在`)
      }
    }, 120 * 1000)
    return res.json({
        code: "0",
        data: {
          filename: req.file.filename,
          size: req.file.size
        },
        msg: '成功',
        success: true
    })
});

module.exports = router;